<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.2">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/icon.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/icon.png">
  <link rel="mask-icon" href="/blog/images/icon.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"bgape002.gitee.io","root":"/blog/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="魔术方法 描述    new 创建类并返回这个类的实例   init 可理解为“构造函数”，在对象初始化的时候调用，使用传入的参数初始化该实例   del 可理解为“析构函数”，当一个对象进行垃圾回收时调用   metaclass 定义当前类的元类   class 查看对象所属的类   base 获取当前类的父类   bases 获取当前类的所有父类   str 定义当前类的实例的文本显示内">
<meta property="og:type" content="article">
<meta property="og:title" content="python魔法方法">
<meta property="og:url" content="https://bgape002.gitee.io/2022/07/06/python%E9%AD%94%E6%B3%95%E6%96%B9%E6%B3%95/index.html">
<meta property="og:site_name" content="bgape002">
<meta property="og:description" content="魔术方法 描述    new 创建类并返回这个类的实例   init 可理解为“构造函数”，在对象初始化的时候调用，使用传入的参数初始化该实例   del 可理解为“析构函数”，当一个对象进行垃圾回收时调用   metaclass 定义当前类的元类   class 查看对象所属的类   base 获取当前类的父类   bases 获取当前类的所有父类   str 定义当前类的实例的文本显示内">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://bgape002.gitee.io/blog/images/magic1.png">
<meta property="og:image" content="https://bgape002.gitee.io/blog/images/magic2.png">
<meta property="og:image" content="https://bgape002.gitee.io/blog/images/magic3.png">
<meta property="og:image" content="https://bgape002.gitee.io/blog/images/magic4.png">
<meta property="og:image" content="https://bgape002.gitee.io/blog/images/magic5.png">
<meta property="article:published_time" content="2022-07-06T06:51:48.000Z">
<meta property="article:modified_time" content="2022-07-06T08:35:48.163Z">
<meta property="article:author" content="bgape002">
<meta property="article:tag" content="magicMethod">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://bgape002.gitee.io/blog/images/magic1.png">

<link rel="canonical" href="https://bgape002.gitee.io/2022/07/06/python%E9%AD%94%E6%B3%95%E6%96%B9%E6%B3%95/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>python魔法方法 | bgape002</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">bgape002</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">淡泊明志，宁静致远</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">66</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">27</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">61</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://bgape002.gitee.io/2022/07/06/python%E9%AD%94%E6%B3%95%E6%96%B9%E6%B3%95/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/head.png">
      <meta itemprop="name" content="bgape002">
      <meta itemprop="description" content="mail: bgape002@163.com">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="bgape002">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          python魔法方法
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2022-07-06 14:51:48 / 修改时间：16:35:48" itemprop="dateCreated datePublished" datetime="2022-07-06T14:51:48+08:00">2022-07-06</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/python/" itemprop="url" rel="index"><span itemprop="name">python</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/blog/2022/07/06/python%E9%AD%94%E6%B3%95%E6%96%B9%E6%B3%95/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/blog/2022/07/06/python%E9%AD%94%E6%B3%95%E6%96%B9%E6%B3%95/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <table>
<thead>
<tr>
<th>魔术方法</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td><strong>new</strong></td>
<td>创建类并返回这个类的实例</td>
</tr>
<tr>
<td><strong>init</strong></td>
<td>可理解为“构造函数”，在对象初始化的时候调用，使用传入的参数初始化该实例</td>
</tr>
<tr>
<td><strong>del</strong></td>
<td>可理解为“析构函数”，当一个对象进行垃圾回收时调用</td>
</tr>
<tr>
<td><strong>metaclass</strong></td>
<td>定义当前类的元类</td>
</tr>
<tr>
<td><strong>class</strong></td>
<td>查看对象所属的类</td>
</tr>
<tr>
<td><strong>base</strong></td>
<td>获取当前类的父类</td>
</tr>
<tr>
<td><strong>bases</strong></td>
<td>获取当前类的所有父类</td>
</tr>
<tr>
<td><strong>str</strong></td>
<td>定义当前类的实例的文本显示内容</td>
</tr>
<tr>
<td><strong>getattribute</strong></td>
<td>定义属性被访问时的行为</td>
</tr>
<tr>
<td><strong>getattr</strong></td>
<td>定义试图访问一个不存在的属性时的行为</td>
</tr>
<tr>
<td><strong>setattr</strong></td>
<td>定义对属性进行赋值和修改操作时的行为</td>
</tr>
<tr>
<td><strong>delattr</strong></td>
<td>定义删除属性时的行为</td>
</tr>
<tr>
<td><strong>copy</strong></td>
<td>定义对类的实例调用 copy.copy() 获得对象的一个浅拷贝时所产生的行为</td>
</tr>
<tr>
<td><strong>deepcopy</strong></td>
<td>定义对类的实例调用 copy.deepcopy() 获得对象的一个深拷贝时所产生的行为</td>
</tr>
</tbody></table>
<span id="more"></span>

<table>
<thead>
<tr>
<th>魔术方法</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td><strong>eq</strong></td>
<td>定义相等符号“==”的行为</td>
</tr>
<tr>
<td><strong>ne</strong></td>
<td>定义不等符号“!=”的行为</td>
</tr>
<tr>
<td><strong>lt</strong></td>
<td>定义小于符号“&lt;”的行为</td>
</tr>
<tr>
<td><strong>gt</strong></td>
<td>定义大于符号“&gt;”的行为</td>
</tr>
<tr>
<td><strong>le</strong></td>
<td>定义小于等于符号“&lt;=”的行为</td>
</tr>
<tr>
<td><strong>ge</strong></td>
<td>定义大于等于符号“&gt;=”的行为</td>
</tr>
<tr>
<td><strong>add</strong></td>
<td>实现操作符“+”表示的加法</td>
</tr>
<tr>
<td><strong>sub</strong></td>
<td>实现操作符“-”表示的减法</td>
</tr>
<tr>
<td><strong>mul</strong></td>
<td>实现操作符“*”表示的乘法</td>
</tr>
<tr>
<td><strong>div</strong></td>
<td>实现操作符“/”表示的除法</td>
</tr>
<tr>
<td><strong>mod</strong></td>
<td>实现操作符“％”表示的取模(求余数)</td>
</tr>
<tr>
<td><strong>pow</strong></td>
<td>实现操作符“**”表示的指数操作</td>
</tr>
<tr>
<td><strong>and</strong></td>
<td>实现按位与操作</td>
</tr>
<tr>
<td><strong>or</strong></td>
<td>实现按位或操作</td>
</tr>
<tr>
<td><strong>xor</strong></td>
<td>实现按位异或操作</td>
</tr>
<tr>
<td><strong>len</strong></td>
<td>用于自定义容器类型，表示容器的长度</td>
</tr>
<tr>
<td><strong>getitem</strong></td>
<td>用于自定义容器类型，定义当某一项被访问时，使用 self[key] 所产生的行为</td>
</tr>
<tr>
<td><strong>setitem</strong></td>
<td>用于自定义容器类型，定义执行 self[key]=value 时产生的行为</td>
</tr>
<tr>
<td><strong>delitem</strong></td>
<td>用于自定义容器类型，定义一个项目被删除时的行为</td>
</tr>
<tr>
<td><strong>iter</strong></td>
<td>用于自定义容器类型，一个容器迭代器</td>
</tr>
<tr>
<td><strong>reversed</strong></td>
<td>用于自定义容器类型，定义当 reversed( ) 被调用时的行为</td>
</tr>
<tr>
<td><strong>contains</strong></td>
<td>用于自定义容器类型，定义调用 in 和 not in 来测试成员是否存在的时候所产生的行为</td>
</tr>
<tr>
<td><strong>missing</strong></td>
<td>用于自定义容器类型，定义在容器中找不到 key 时触发的行为</td>
</tr>
<tr>
<td><strong>abs</strong></td>
<td>取绝对值abs()</td>
</tr>
</tbody></table>
<p><img src="/blog/images/magic1.png" alt="."></p>
<p><img src="/blog/images/magic2.png" alt="."></p>
<p><img src="/blog/images/magic3.png" alt="."></p>
<p><img src="/blog/images/magic4.png" alt="."></p>
<p><img src="/blog/images/magic5.png" alt="."></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Vector</span>:</span><br><span class="line">    a = <span class="literal">None</span></span><br><span class="line">    b = <span class="literal">None</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, a, b</span>):</span><br><span class="line">        self.a = a</span><br><span class="line">        self.b = b</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__str__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27;向量(%d, %d)&#x27;</span>  % (self.a, self.b)</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__add__</span> (self, other):</span><br><span class="line">        <span class="keyword">return</span> Vector(self.a + other.a, self.b + other.b)</span><br><span class="line">    <span class="keyword">def</span>  <span class="title function_">__sub__</span>(<span class="params">self, other</span>):</span><br><span class="line">        <span class="keyword">return</span> Vector(self.a - other.a, self.b - other.b)</span><br><span class="line"></span><br><span class="line">v1 = Vector(<span class="number">1</span>, <span class="number">2</span>)</span><br><span class="line">v2 = Vector(<span class="number">3</span>, <span class="number">4</span> )</span><br><span class="line">    <span class="built_in">print</span>(v1, <span class="string">&quot; + &quot;</span>, v2, <span class="string">&quot;=&quot;</span>, v1 + v2)</span><br><span class="line">    <span class="built_in">print</span>(v1, <span class="string">&quot; - &quot;</span>, v2, <span class="string">&quot;=&quot;</span>, v1 - v2)</span><br><span class="line">   </span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;output</span></span><br><span class="line"><span class="string">class Vector:</span></span><br><span class="line"><span class="string"><span class="meta">... </span>         a = None</span></span><br><span class="line"><span class="string"><span class="meta">... </span>         b = None</span></span><br><span class="line"><span class="string"><span class="meta">... </span>         def __init__(self, a, b):</span></span><br><span class="line"><span class="string"><span class="meta">... </span>             self.a = a</span></span><br><span class="line"><span class="string"><span class="meta">... </span>             self.b = b</span></span><br><span class="line"><span class="string"><span class="meta">... </span>         def __str__(self):</span></span><br><span class="line"><span class="string"><span class="meta">... </span>             return &#x27;向量(%d, %d)&#x27;  % (self.a, self.b)</span></span><br><span class="line"><span class="string"><span class="meta">... </span>         def __add__ (self, other):</span></span><br><span class="line"><span class="string"><span class="meta">... </span>             return Vector(self.a + other.a, self.b + other.b)</span></span><br><span class="line"><span class="string"><span class="meta">... </span>         def  __sub__(self, other):</span></span><br><span class="line"><span class="string"><span class="meta">... </span>             return Vector(self.a - other.a, self.b - other.b)</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string"><span class="meta">&gt;&gt;&gt; </span>v1 = Vector(1, 2)</span></span><br><span class="line"><span class="string"><span class="meta">&gt;&gt;&gt; </span>v2 = Vector(3, 4 )</span></span><br><span class="line"><span class="string"><span class="meta">&gt;&gt;&gt; </span>print(v1, &quot; + &quot;, v2, &quot;=&quot;, v1 + v2)</span></span><br><span class="line"><span class="string">向量(1, 2)  +  向量(3, 4) = 向量(4, 6)</span></span><br><span class="line"><span class="string"><span class="meta">&gt;&gt;&gt; </span>print(v1, &quot; - &quot;, v2, &quot;=&quot;, v1 - v2)</span></span><br><span class="line"><span class="string">向量(1, 2)  -  向量(3, 4) = 向量(-2, -2)</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>





<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;类的魔法方法和成员方法</span></span><br><span class="line"><span class="string">package &gt;&gt; pymagic</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Cat</span>:</span><br><span class="line">    <span class="string">&quot;&quot;&quot;cat类&quot;&quot;&quot;</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, age=<span class="literal">None</span></span>):</span><br><span class="line">        self.name = <span class="string">&#x27;Cname&#x27;</span></span><br><span class="line">        self.__private = <span class="string">&#x27;private&#x27;</span>   <span class="comment"># 私有变量，无法直接访问。可使用cat._Cat__private强制访问</span></span><br><span class="line">        self.age = age</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__del__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;我在del cat或程序结束时会执行，即变量被回收时执行&#x27;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__call__</span>(<span class="params">self, *args, **kwargs</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;cat: &quot;</span>, args, kwargs, <span class="string">&quot;你可以用类似函数调用的方法调用Cat类，如cat(a,b,c)&quot;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__str__</span>(<span class="params">self</span>):  <span class="comment"># 改变类输出的形式</span></span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27;我是：&#x27;</span> + self.name</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__int__</span>(<span class="params">self</span>):</span><br><span class="line">        ...</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__float__</span>(<span class="params">self</span>):</span><br><span class="line">        ...</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__new__</span>(<span class="params">cls, *args, **kwargs</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        1.在一个对象实例化的时候调用的第一个方法</span></span><br><span class="line"><span class="string">        2.cls代表类的名称，表示该类，其他的参数是用来直接传递给__init__方法</span></span><br><span class="line"><span class="string">        3.决定是否要用__init__方法。可以调用其他的构造方法或直接返回别的实例对象作为本类的实例。如果没有返回实例对象，则__init__不会被调用</span></span><br><span class="line"><span class="string">        4.用于继承一个不可变的类型，比如tuple或string</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">if</span> <span class="built_in">len</span>(args) <span class="keyword">and</span> args[<span class="number">0</span>]&gt;<span class="number">50</span>:</span><br><span class="line">            <span class="built_in">print</span>(<span class="string">&quot;the cat is died.&quot;</span>)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="built_in">object</span>.__new__(cls)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__len__</span>(<span class="params">self</span>):</span><br><span class="line">        ...</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__iter__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">iter</span>(self.name)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__getitem__</span>(<span class="params">self, item</span>):</span><br><span class="line">        <span class="keyword">if</span> self.name != item:</span><br><span class="line">            <span class="keyword">return</span> self.name</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__setitem__</span>(<span class="params">self, key, value</span>):</span><br><span class="line">        <span class="keyword">if</span> self.name != key:</span><br><span class="line">            self.name = value</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__delitem__</span>(<span class="params">self, key</span>):</span><br><span class="line">        <span class="keyword">if</span> key == <span class="string">&#x27;name&#x27;</span>:</span><br><span class="line">            <span class="keyword">del</span> self.name</span><br><span class="line">            <span class="built_in">print</span>(<span class="string">&#x27;delitem操作&#x27;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__add__</span>(<span class="params">self, other</span>):</span><br><span class="line">        ...</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__sub__</span>(<span class="params">self, other</span>):</span><br><span class="line">        ...</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__mul__</span>(<span class="params">self, other</span>):</span><br><span class="line">        ...</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__truediv__</span>(<span class="params">self, other</span>):</span><br><span class="line">        ...</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__floordiv__</span>(<span class="params">self, other</span>):</span><br><span class="line">        ...</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__mod__</span>(<span class="params">self, other</span>):</span><br><span class="line">        ...</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__pow__</span>(<span class="params">self, power, modulo=<span class="literal">None</span></span>):</span><br><span class="line">        ...</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    cat = Cat()</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 成员方法</span></span><br><span class="line">    <span class="built_in">print</span>(cat.__dict__)  <span class="comment"># 类的成员变量字典</span></span><br><span class="line">    <span class="built_in">print</span>(cat.__doc__)  <span class="comment"># 类的描述信息</span></span><br><span class="line">    <span class="built_in">print</span>(cat.__module__)  <span class="comment"># 模块名称</span></span><br><span class="line">    <span class="built_in">print</span>(cat.__dir__())  <span class="comment"># 列出对象的所有属性（方法）名</span></span><br><span class="line"></span><br><span class="line">    obj = <span class="built_in">object</span>()</span><br><span class="line">    <span class="built_in">print</span>(obj.__dir__())</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;测试魔法方法好成员方法功能</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">import</span> pymagic <span class="keyword">as</span> pm</span><br><span class="line"></span><br><span class="line">dcat = pm.Cat(<span class="number">60</span>)</span><br><span class="line"><span class="built_in">print</span>(dcat)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;###############split##############&#x27;</span>)</span><br><span class="line">cat = pm.Cat(<span class="number">10</span>)</span><br><span class="line"><span class="built_in">print</span>(cat.__new__.__doc__)</span><br><span class="line"><span class="built_in">print</span>(cat._Cat__private)</span><br><span class="line"><span class="comment"># 成员方法</span></span><br><span class="line"><span class="built_in">print</span>(cat.__dict__)</span><br><span class="line"><span class="built_in">print</span>(cat.__doc__)</span><br><span class="line"><span class="built_in">print</span>(cat.__module__)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;###############split##############&#x27;</span>)</span><br><span class="line"><span class="comment"># 魔法方法</span></span><br><span class="line"><span class="comment"># __call__</span></span><br><span class="line">cat(<span class="string">&#x27;meow&#x27;</span>, <span class="string">&#x27;moew&#x27;</span>)</span><br><span class="line"><span class="comment"># __str__</span></span><br><span class="line"><span class="built_in">print</span>(cat)</span><br><span class="line"><span class="comment"># __iter__</span></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> cat:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;iter:&#x27;</span>, i)</span><br><span class="line"><span class="comment"># __getitem__  __setitem__  __delitem__  让类支持[]形式的操作</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;getitem&#x27;</span>, cat[<span class="string">&#x27;dog&#x27;</span>])</span><br><span class="line">cat[<span class="string">&#x27;dog&#x27;</span>] = <span class="string">&#x27;dog&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(cat.name)</span><br><span class="line"><span class="comment"># 运算符重载 + __add__ | - __sub__ | * __mul__ | / __truediv__ | // __floordiv__ | % __mod__ | ** __pow__</span></span><br><span class="line"><span class="keyword">del</span> cat[<span class="string">&#x27;name&#x27;</span>]</span><br><span class="line"><span class="comment"># __del__</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;print infos</span></span><br><span class="line"><span class="string">the cat is died.</span></span><br><span class="line"><span class="string">None</span></span><br><span class="line"><span class="string">###############split##############</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">        1.在一个对象实例化的时候调用的第一个方法</span></span><br><span class="line"><span class="string">        2.cls代表类的名称，表示该类，其他的参数是用来直接传递给__init__方法</span></span><br><span class="line"><span class="string">        3.决定是否要用__init__方法。可以调用其他的构造方法或直接返回别的实例对象作为本类的实例。如果没有返回实例对象，则__init__不会被调用</span></span><br><span class="line"><span class="string">        4.用于继承一个不可变的类型，比如tuple或string</span></span><br><span class="line"><span class="string">        </span></span><br><span class="line"><span class="string">private</span></span><br><span class="line"><span class="string">&#123;&#x27;name&#x27;: &#x27;Cname&#x27;, &#x27;_Cat__private&#x27;: &#x27;private&#x27;, &#x27;age&#x27;: 10&#125;</span></span><br><span class="line"><span class="string">cat类</span></span><br><span class="line"><span class="string">base.pymagic</span></span><br><span class="line"><span class="string">###############split##############</span></span><br><span class="line"><span class="string">cat:  (&#x27;meow&#x27;, &#x27;moew&#x27;) &#123;&#125; 你可以用类似函数调用的方法调用Cat类，如cat(a,b,c)</span></span><br><span class="line"><span class="string">我是：Cname</span></span><br><span class="line"><span class="string">iter: C</span></span><br><span class="line"><span class="string">iter: n</span></span><br><span class="line"><span class="string">iter: a</span></span><br><span class="line"><span class="string">iter: m</span></span><br><span class="line"><span class="string">iter: e</span></span><br><span class="line"><span class="string">getitem Cname</span></span><br><span class="line"><span class="string">dog</span></span><br><span class="line"><span class="string">delitem操作</span></span><br><span class="line"><span class="string">我在del cat或程序结束时会执行，即变量被回收时执行</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>









<h3 id="参考链接"><a href="#参考链接" class="headerlink" title="参考链接"></a>参考链接</h3><font size=2>

<p>[1] <a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV1QY4y147K5?p=8&vd_source=5f03bdbb9a8460c7ae08f9cdea23577b">Python高级核心技术97讲</a></p>
<p>[2] <a target="_blank" rel="noopener" href="http://c.biancheng.net/view/7817.html">Python常用魔术方法一览表</a></p>
<p>[3] <a target="_blank" rel="noopener" href="https://blog.csdn.net/jasonLee_lijiaqi/article/details/79332593?spm=1001.2101.3001.6661.1&utm_medium=distribute.pc_relevant_t0.none-task-blog-2~default~CTRLIST~default-1-79332593-blog-109060313.pc_relevant_multi_platform_whitelistv1_exp2&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2~default~CTRLIST~default-1-79332593-blog-109060313.pc_relevant_multi_platform_whitelistv1_exp2&utm_relevant_index=1">python所有的魔法方法汇总</a></p>
<p></font>&gt;</p>

    </div>

    
    
    

      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/blog/tags/magicMethod/" rel="tag"><i class="fa fa-tag"></i> magicMethod</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2022/07/05/collections-package/" rel="prev" title="collections package">
      <i class="fa fa-chevron-left"></i> collections package
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2022/07/06/python%E7%BA%BF%E7%A8%8B%E6%B1%A0/" rel="next" title="python线程池">
      python线程池 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>


        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%82%E8%80%83%E9%93%BE%E6%8E%A5"><span class="nav-number">1.</span> <span class="nav-text">参考链接</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="bgape002"
      src="/blog/images/head.png">
  <p class="site-author-name" itemprop="name">bgape002</p>
  <div class="site-description" itemprop="description">mail: bgape002@163.com</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">61</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">27</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">66</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2021 – 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">bgape002</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  




  
<script src="/blog/js/local-search.js"></script>











<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'forest',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'szhBf0Qamzsowubi1WnkXmUj-gzGzoHsz',
      appKey     : 'WpwxoK0fVJHvhzWwakr9vbpA',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : '' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
